<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/4/12
 * Time: 2:43 PM
 */

namespace app\api\controller\v38;

use app\api\controller\v2\Auth;
use app\common\cachemodel\FortuneNote;
use app\common\cachemodel\lucky\AppUserLuckyChangeRecord;
use app\common\cachemodel\lucky\AppUserLuckyInfo;
use app\common\cachemodel\Recode;
use app\common\cachemodel\zl2\AstroFortuneChange as AstroFortuneChangeModel;
use app\common\lib\util\Time;
use app\common\lib\Util;
use think\Env;
use think\response\Json;

class MoodNote extends Auth
{
    /**
     * @throws \Exception
     */
    public function index()
    {
        $date = input('date/s', '');
        $nowDate = date('Y-m-d');
        if (!$date)
        {
            $date = $nowDate;
        }
        $dateTime = date('Y-m-d', strtotime($date));
        if ($date !== $dateTime)
        {   // 日期格式错误
            return show(config('code.error'), '服务异常,请稍后重试');
        }
        $timeTmp = strtotime($dateTime);
        $nowDateTime = strtotime($nowDate);

        $appMoodNoteModel = new FortuneNote();
        $noteInfo = $appMoodNoteModel->getNoteLists($this->user['id'], 2);
        $todayRankInfo = $noteInfo ? array_column($noteInfo, null, 'time') : [];
        if (isset($todayRankInfo[$timeTmp]))
        {   // 已签到
            if ($timeTmp <= $nowDateTime && $timeTmp >= $nowDateTime - 172800)
            {   // 不是未来日期   且  三天以内   今天 昨日 + 前天    前天时间 = 今天 - 172800
                $status = 1;    // 已签到 可以编辑
            } else
            {   // 未来日期 不支持 编辑签到 或者 距离今日超过3天
                $status = 2;    // 已签到 不支持编辑签到
            }
            // 获取当前日期 签到详情
            $id = (int)$todayRankInfo[$timeTmp]['id'];
            $modeNoteInfo = $appMoodNoteModel->getInfoById($id);
            $moodTagConfig = config('mood');
            $tagList = [];
            foreach ($modeNoteInfo['tids'] as $tidItem)
            {
                $tagList[] = [
                    'id' => $tidItem,
                    'name' => $moodTagConfig['tag_list'][$tidItem]['name'],
                ];
            }
            $resMoodInfo = [
                'icon' => $moodTagConfig['mood_list'][$modeNoteInfo['mood']]['icon'] . '.png',
                'name' => $moodTagConfig['mood_list'][$modeNoteInfo['mood']]['name'],
                'id' => $modeNoteInfo['mood'],
                'tag_list' => $tagList,
                'content' => $status === 1 ? $modeNoteInfo['content'] : '',
                'desire' => $status === 1 ? $modeNoteInfo['desire'] : '',
                'record_id' => $id,
            ];

            if ($moodTagConfig['mood_list'][$modeNoteInfo['mood']]['type'] > 3)
            {   // 开心
                $text = "这一天的心情还不错，希望你每天都有好心情";
                $moodStatus = 1;
            } elseif ($moodTagConfig['mood_list'][$modeNoteInfo['mood']]['type'] === 3)
            {   // 平平
                $text = "这一天的心情平平无奇，但是人生的每一天都不平凡";
                $moodStatus = 2;
            } else
            {   // 伤心
                $text = "这一天的心情不是很好，忘掉不开心吧～";
                $moodStatus = 3;
            }
            $tipInfo = [
                'icon' => '',
                'text' => $text
            ];

            if ($timeTmp === $nowDateTime)
            {   // 已签到 获取 天象运势信息
                $astroData = (new AstroFortuneChangeModel())->getAstroFortuneChangeUnderwayList($this->user['id'], $timeTmp, $moodStatus, 3);
            }
        } else
        {   // 未签到
            $tipInfo = ['icon' => Env::get('host.photo') . '/test/mood/tip_icon.png'];
            $tipInfo['text'] = '';
            if ($timeTmp <= $nowDateTime && $timeTmp >= $nowDateTime - 172800)
            {   // 不是未来日期   且  三天以内   今天 昨日 + 前天    前天时间 = 今天 - 172800
                $status = 0;
            } else
            {   // 未来日期 不支持 签到 或者 距离今日超过3天
                $status = -1;
                $tipInfo['text'] = "很遗憾这一天你没有记录心情，我也很好奇这一天\r\n你的心情怎么样？\r\n接下来的每一天都要记录哦~";
            }
        }

        $resData = [
            'server_time' => $nowDate,
            'status' => $status,
            'tip' => $tipInfo,
            'mood_info' => $resMoodInfo ?? null,
            'mood_record_num_des' => '记录了' . count($todayRankInfo) . '天心情',
            'fortune_list' => $astroData ?? [], // 根据 日期 签到心情筛选天象运势
            'rank_tips' => [],
            'note_times_list' => $appMoodNoteModel->CheckFortuneSevenUnlockStatus($this->user['id'], $dateTime)['day_list']

        ];
        //获取今日所有笔记
        $res = $appMoodNoteModel->where(['time' => strtotime(date('Y-m-d')), 'tids' => ['neq', '']])->column('*', 'id');
        if ($res && $this->user['rid'])
        {
            $todayTotalRankInfo = $appMoodNoteModel->getNoteRank($this->user['rid'], $res);
            $todaySign = array_keys($todayTotalRankInfo['today_rank']);
            // 获取星座名称配置
            $sign_name = config('astrolog.sign_name');
            $resData['rank_tips'] = [
                '最开心：' . mb_substr(explode('|', $sign_name[current($todaySign)])[3], 0, 2),
            ];
            if ($todayTotalRankInfo['today_rank'][12])
            {
                $resData['rank_tips'][] = '最EMO：' . mb_substr(explode('|', $sign_name[end($todaySign)])[3], 0, 2);
            }
            if ($todayTotalRankInfo['self_rank'])
            {
                $resData['rank_tips'][] = '当前排名：' . $todayTotalRankInfo['self_rank'];

            }
        }
        return show(config('code.success'), 'success', $resData);
    }

    /**
     * 列表
     * @return array|mixed
     * @throws \Exception
     */
    public function list()
    {
        $appMoodNoteModel = new FortuneNote();

        $resData = $appMoodNoteModel->getNotePageAll($this->user['id'], 0);
        $moodTagConfig = config('mood');
        $res = [];
        $oldMoodCOnfig = [
            1 => 9, //  平静
            2 => 5, //  开心
            3 => 1, //  兴奋
            4 => 14, //  疲惫
            5 => 18, //  难过
        ];
        foreach ($resData['data'] as $item)
        {
            if (!empty($item['tids']))
            {
                $tids = explode(',', $item['tids']);
                foreach ($tids as $k => $tid)
                {
                    $tids[$k] = (int)$tid;
                }
            } else
            {
                $tids = [];
                if ((int)$item['sign_id'] === 0)
                {   // 旧日记
                    $item['mood'] = $oldMoodCOnfig[$item['mood']] ?? $item['mood'];
                }
            }

            $tmp = [
                'id' => (int)$item['id'],
                'mood_id' => (int)$item['mood'],
                'mood_icon' => $moodTagConfig['mood_list'][$item['mood']]['icon'] . '.png',
                'mood_name' => $moodTagConfig['mood_list'][$item['mood']]['name'],
                'content' => $item['content'],
                'desire' => $item['desire'],
                'state' => $tids ? null : (int)$item['state'],
                'create_time' => $item['time'] ? date('Y.m.d', $item['time']) : '',
                'update_time' => $item['update_time'] ? date('Y.m.d H:i:s', $item['update_time']) : '',
                'tags' => []
            ];

            foreach ($tids as $tid)
            {
                $tmp['tags'][] = [
                    'id' => (int)$tid,
                    'name' => $moodTagConfig['tag_list'][$tid]['name'],
                ];
            }
            $res[] = $tmp;
        }
        $resData['data'] = $res;
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 添加
     * @return \think\response\Json
     * @throws \Exception
     */
    public function save()
    {
        $moodId = input('mood_id/d', 0);
        $tagIds = input('tag_ids/s', '');
        $content = input('content/s', '');
        $desire = input('desire/s', '');
        $date = input('date/s', '');

        $moodTagConfig = config('mood');
        $nowTime = $this->request->time();

        if (!isset($moodTagConfig['mood_list'][$moodId]) || empty($tagIds) || empty($date) || mb_strlen($content) > 500 || mb_strlen($desire) > 500)
        {
            return show(config('code.error'), '请求异常,请稍后重试');
        }

        $tagIdsArr = explode(',', $tagIds);
        if (count($tagIdsArr) > 3)
        {
            return show(config('code.error'), '请求异常,请稍后重试');
        }

        foreach ($tagIdsArr as $tid)
        {
            if (!isset($moodTagConfig['tag_list'][$tid]))
            {
                return show(config('code.error'), '请求异常,请稍后重试');
            }
        }

        $dateTime = date('Y-m-d', strtotime($date));
        if ($date !== $dateTime)
        {   // 日期格式错误
            return show(config('code.error'), '请求异常,请稍后重试');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'noteAdd', 'mood_id' => $moodId, 'tag_ids' => $tagIds, 'content' => $content, 'date' => $date], 10))
        {
            return show(config('code.error'), '操作频繁,请稍后重试');
        }

        $timeTmp = strtotime($dateTime);
        // 客户端 当前日期
        $nowDateTime = strtotime(date('Y-m-d'));
        if ($timeTmp > $nowDateTime || $timeTmp < $nowDateTime - 172800)
        {   // 不支持 签到
            return show(config('code.error'), '只能记录前天、昨天、今天的心情');
        }

        $appMoodNoteModel = new FortuneNote();
        $noteInfo = $appMoodNoteModel->getNoteLists($this->user['id'], 2);
        $noteTimes = $noteInfo ? array_column($noteInfo, null, 'time') : [];
        // 获取 已解锁 日期
        if (isset($noteTimes[$timeTmp]))
        {   // 已添加
            return show(config('code.error'), "当天心情已记录");
        }
        if ($this->user['rid'])
        {
            $recode = (new Recode)->getInfoById($this->user['rid']);
            $signId = explode('-', $recode['sun'])[0];
        } else
        {
            $signId = 0;
        }
        $insertData = [
            'uid' => $this->user['id'],
            'rid' => $this->user['rid'],
            'sign_id' => $signId,
            'time' => $timeTmp,
            'mood' => $moodId,
            'tids' => $tagIds,
            'content' => $content,
            'desire' => $desire,
            'from' => 1,
            'create_time' => $nowTime
        ];

        $id = $appMoodNoteModel->SaveData($insertData);

        if ($id)
        {
            if ($timeTmp === strtotime(date('Y-m-d', $nowTime)))
            {
                //只有今日签到才奖励幸运星
                $todayNoteInfo = $appMoodNoteModel->checkTodayNoteStatus($this->user['id']);
                if (empty($todayNoteInfo))
                {   // 今天未签到
                    $luckyTaskConfig = config('lucky_task');
                    $res = (new AppUserLuckyInfo())->userLuckyNumSend($this->user['id'], 8, '签到');
                    if ($res)
                    {
                        (new AppUserLuckyChangeRecord())->updateSignInData($this->user['id'], date('Ymd', $timeTmp), [
                            'num' => 10,
                            'time' => $this->request->time()
                        ]);
                        $data = [
                            'lucky_toast' => [
                                "title" => $luckyTaskConfig['task_list'][8]['toast_name'],
                                "img" => $luckyTaskConfig['task_list'][8]['img'],
                                "des" => "x{$luckyTaskConfig['task_list'][8]['lucky_num']}已领取"
                            ]
                        ];
                    }
                }
            }
            return show(config('code.success'), 'success.', $data ?? []);
        }
        return show(config('code.error'), '服务异常,请稍后重试');
    }

    /**
     * 更新
     * @return \think\response\Json
     * @throws \Exception
     */
    public function update()
    {
        $moodId = input('mood_id/d', 0);
        $tagIds = input('tag_ids/s', '');
        $content = input('content/s', '');
        $desire = input('desire/s', '');
        $recordId = input('id/d', 0);
        $state = input('state/d', -1);
        $nowTime = $this->request->time();

        if ($recordId <= 0 || mb_strlen($content) > 500 || mb_strlen($desire) > 500)
        {
            return show(config('code.error'), '请求异常,请稍后重试');
        }

        $appMoodNoteModel = new FortuneNote();
        $moodNoteInfo = $appMoodNoteModel->getInfoById($recordId);
        if (empty($moodNoteInfo) || (int)$moodNoteInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常,数据不存在');
        }

        //区分新版旧版笔记
        if (empty($moodNoteInfo['tids']))
        {
            $updateData = [
                'content' => $content,
                'update_time' => $nowTime
            ];
        } else
        {
            if ($moodId)
            {
                $moodTagConfig = config('mood');
                if (!isset($moodTagConfig['mood_list'][$moodId]) || empty($tagIds))
                {
                    return show(config('code.error'), '请求异常,请稍后重试');
                }
                $tagIdsArr = explode(',', $tagIds);
                if (count($tagIdsArr) > 3)
                {
                    return show(config('code.error'), '请求异常,请稍后重试');
                }
                foreach ($tagIdsArr as $tid)
                {
                    if (!isset($moodTagConfig['tag_list'][$tid]))
                    {
                        return show(config('code.error'), '请求异常,请稍后重试');
                    }
                }
            }

            if (!$moodId)
            {
                $moodId = $moodNoteInfo['mood'];
                $tagIds = implode(',', $moodNoteInfo['tids']);
            } else
            {
                // 客户端 当前日期
                $nowDateTime = strtotime(date('Y-m-d'));
                if ($moodNoteInfo['time'] > $nowDateTime || $moodNoteInfo['time'] < $nowDateTime - 172800)
                {   // 不支持 编辑心情 及 标签
                    $moodId = $moodNoteInfo['mood'];
                    $tagIds = count($moodNoteInfo['tids']) > 1 ? implode(',', $moodNoteInfo['tids']) : current($moodNoteInfo['tids']);
                }
            }
            $updateData = [
                'mood' => $moodId,
                'tids' => $tagIds,
                'content' => $content,
                'desire' => $desire,
                'update_time' => $nowTime
            ];
        }
        $res = $appMoodNoteModel->UpdateData($recordId, $updateData);
        if ($res)
        {
            return show(config('code.success'), 'success.');
        }
        return show(config('code.error'), '服务异常,请稍后重试');
    }

    /**
     * 删除
     * @return \think\response\Json
     * @throws \Exception
     */
    public function del()
    {
        $recordId = input('id/d', 0);
        if ($recordId <= 0)
        {
            return show(config('code.error'), '服务异常,请稍后重试');
        }
        $res = (new FortuneNote())->DeleteData($recordId, $this->user['id']);
        if ($res)
        {
            return show(config('code.success'), 'success.');
        }

        return show(config('code.error'), '服务异常,请稍后重试');
    }

    /**
     * 获取心情和标签信息
     * @return \think\response\Json
     */
    public function getMoodAndTag()
    {
        $moodTagConfig = config('mood');

        $moodList = [];
        foreach ($moodTagConfig['mood_list'] as $item)
        {
            $tmp = [
                'id' => $item['id'],
                'name' => $item['name'],
                'icon' => $item['icon'] . '.png',
            ];
            if ($item['type'] > 3)
            {   // 开心
                $tmp['des'] = "这一天的心情还不错，希望你每天都有好心情";
            } elseif ($item['type'] === 3)
            {   // 平平
                $tmp['des'] = "这一天的心情平平无奇，但是人生的每一天都不平凡";
            } else
            {   // 伤心
                $tmp['des'] = "这一天的心情不是很好，忘掉不开心吧～";
            }
            $moodList[] = $tmp;
        }

        return show(config('code.success'), '请求成功', [
            'mood_list' => $moodList,
            'tag_list' => array_values($moodTagConfig['tag_list']),
        ]);
    }

    /**
     * 心情笔记签到日历
     * @return Json
     * @throws \Exception
     */
    public function signCalendar()
    {
//        $startTime = input('start_time/s', '');
        $endTime = input('end_time/s', '');
        $timeRange = Time::getNowTimeMonthRange($endTime, 3);
        $timeRange = array_flip_key_value($timeRange);
        $fortuneNote = new FortuneNote();
        $data = $fortuneNote->getNoteLists($this->user['id'], 2);
        $res = $fortuneNote->getTimeRangeNote($data, $timeRange);
        return show(config('code.success'), 'Success.', $res);
    }
}
